<template>
  <div class="spec-combination-selector">
    <div v-if="specList.length === 0" class="no-specs">
      <el-alert
        title="暂无规格配置"
        description="请先在规格配置区域添加商品规格"
        type="warning"
        show-icon
        :closable="false"
      />
    </div>
    
    <div v-else class="spec-selectors">
      <div 
        v-for="spec in specList" 
        :key="spec.id || spec.spec_name"
        class="spec-item"
      >
        <div class="spec-label">
          <span class="spec-name">{{ spec.spec_name }}</span>
          <span class="required" v-if="spec.required">*</span>
        </div>
        
        <div class="spec-values">
          <el-radio-group 
            v-model="selectedValues[spec.spec_name]"
            @change="handleValueChange"
            size="small"
          >
            <el-radio 
              v-for="value in getSpecValues(spec)"
              :key="value"
              :label="value"
              border
            >
              {{ value }}
            </el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>
    
    <!-- 预览选中的规格组合 -->
    <div v-if="hasSelectedValues" class="combination-preview">
      <div class="preview-title">已选择的规格组合：</div>
      <div class="preview-tags">
        <el-tag
          v-for="(value, key) in selectedValues"
          :key="key"
          size="small"
          type="primary"
          style="margin-right: 8px; margin-bottom: 8px;"
        >
          {{ key }}: {{ value }}
        </el-tag>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SpecCombinationSelector',
  props: {
    value: {
      type: String,
      default: '{}'
    },
    specList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      selectedValues: {}
    }
  },
  computed: {
    hasSelectedValues() {
      return Object.keys(this.selectedValues).length > 0 && 
             Object.values(this.selectedValues).some(v => v !== '');
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        if (newVal && newVal !== '{}') {
          try {
            const parsed = JSON.parse(newVal);
            this.selectedValues = { ...parsed };
          } catch (e) {
            this.selectedValues = {};
          }
        } else {
          this.selectedValues = {};
        }
      }
    },
    specList: {
      immediate: true,
      handler(newSpecList) {
        // 如果已有选中值，则合并规格列表，确保所有规格都有对应的空值
        if (newSpecList.length > 0) {
          const currentValues = { ...this.selectedValues };
          newSpecList.forEach(spec => {
            if (!(spec.spec_name in currentValues)) {
              currentValues[spec.spec_name] = '';
            }
          });
          this.selectedValues = currentValues;
        }
      }
    }
  },
  mounted() {
    // 确保在组件挂载后正确处理初始值
    this.$nextTick(() => {
      this.initializeSelectedValues();
    });
  },
  updated() {
    // 在组件更新后也检查初始值
    this.$nextTick(() => {
      if (this.value && this.value !== '{}' && Object.keys(this.selectedValues).length === 0) {
        this.initializeSelectedValues();
      }
    });
  },
  methods: {
    initializeSelectedValues() {
      // 如果有初始值，确保正确设置
      if (this.value && this.value !== '{}') {
        try {
          const parsed = JSON.parse(this.value);
          this.selectedValues = { ...parsed };
        } catch (e) {
          this.selectedValues = {};
        }
      }
    },
    
    getSpecValues(spec) {
      // 处理规格值，可能是字符串数组或JSON字符串
      if (spec.spec_values) {
        if (typeof spec.spec_values === 'string') {
          try {
            return JSON.parse(spec.spec_values);
          } catch (e) {
            return [];
          }
        } else if (Array.isArray(spec.spec_values)) {
          return spec.spec_values;
        }
      }
      return [];
    },
    
    handleValueChange() {
      // 过滤掉空值
      const filteredValues = {};
      Object.keys(this.selectedValues).forEach(key => {
        if (this.selectedValues[key]) {
          filteredValues[key] = this.selectedValues[key];
        }
      });
      
      // 更新v-model
      this.$emit('input', JSON.stringify(filteredValues));
      this.$emit('change', filteredValues);
    },
    
    // 强制刷新选中值
    forceRefresh() {
      this.initializeSelectedValues();
    }
  }
}
</script>

<style scoped lang="scss">
.spec-combination-selector {
  .no-specs {
    margin-bottom: 16px;
  }
  
  .spec-selectors {
    .spec-item {
      margin-bottom: 20px;
      padding: 16px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      background-color: #fafafa;
      
      .spec-label {
        margin-bottom: 12px;
        
        .spec-name {
          font-weight: 500;
          color: #303133;
          font-size: 14px;
        }
        
        .required {
          color: #f56c6c;
          margin-left: 4px;
        }
      }
      
      .spec-values {
        .el-radio-group {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          
          .el-radio {
            margin-right: 0;
            margin-bottom: 8px;
          }
        }
      }
    }
  }
  
  .combination-preview {
    margin-top: 16px;
    padding: 12px;
    background-color: #f0f9ff;
    border: 1px solid #b3d8ff;
    border-radius: 4px;
    
    .preview-title {
      font-size: 12px;
      color: #606266;
      margin-bottom: 8px;
    }
    
    .preview-tags {
      display: flex;
      flex-wrap: wrap;
    }
  }
}
</style> 